#include <kieper/PacketAssembler.hpp>
#include <kieper/PacketHeader.hpp>

#include <google/protobuf/message.h>

namespace kieper {
using ::google::protobuf::Message;

PacketAssembler::PacketAssembler() : nextPacketId_(0) {}
PacketAssembler::~PacketAssembler() {}

PacketHeader PacketAssembler::makePacketHeader(const Message* message, uint16_t messageType) {
    uint16_t currentProtoVersion = protocolVersion();
    uint32_t packetId = nextPacketId();
    return PacketHeader(currentProtoVersion, messageType, packetId);
}

size_t PacketAssembler::makePacket(unsigned char* packetBuffer,
  const PacketHeader* packetHeader, const Message* message) {
    packetHeader->toArray(packetBuffer);
    unsigned char* messageBuffer = packetBuffer + PacketHeader::HEADER_SIZE;
    message->SerializeToArray(messageBuffer, message->ByteSize());
    return PacketHeader::HEADER_SIZE + message->ByteSize();
}

uint16_t PacketAssembler::protocolVersion() const {
    return PROTOCOL_VERSION;
}

uint32_t PacketAssembler::nextPacketId() {
    return nextPacketId_++;
}
}

